package com.dragon.common.util;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信认证数据
 */
public class WechatCheckUtil {


    // token值,可后台配置
    private static String token = "04c2f83a18e49ef6a98917084f8ecc20";


    //wechat token get url
    private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    //添加草稿请求地址
    private static String WECHAT_ADD_DRAT_URL = "https://api.weixin.qq.com/cgi-bin/draft/add";


    //修改草稿
    private static String WECHAT_UPDATE_DRAT_URL = "https://api.weixin.qq.com/cgi-bin/draft/update";

    //删除草稿
    private static String WECHAT_DELETE_DRAT_URL = "https://api.weixin.qq.com/cgi-bin/draft/delete";


    private static String WECHAT_SUMMIT_DRAT_URL = "https://api.weixin.qq.com/cgi-bin/freepublish/submit";

    private static String WECHAT_FOREACH_STATUS_URL = "https://api.weixin.qq.com/cgi-bin/freepublish/get";

    private static String WECHAT_UPLOAD_FILE = "https://api.weixin.qq.com/cgi-bin/material/add_material";

    private static String WECHAT_SELECT_ONE = "https://api.weixin.qq.com/cgi-bin/draft/get";

    //创建菜单
    private static String WECHAT_MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create";
    //查询菜单
    private static String WECHAT_MENU_SELECT_URL = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info";
    //删除菜单
    private static String WECHAT_MENU_DELETE_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete";


    public static Boolean checkSignature(String signature, String timestamp, String nonce){

        String[] arr = new String[]{token,timestamp,nonce};

        sort(arr);

        StringBuilder content = new StringBuilder();

        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        String mdStr = SecureUtil.sha1(content.toString());

        if(mdStr.equals(signature)) return true;

        return false;
    }


    /**
     * 获取access_token
     * @param appId
     * @param secret
     * @return
     */
    public static String getAccessToken(String appId,String secret){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("grant_type","client_credential");
        paramMap.put("appid",appId);
        paramMap.put("secret",secret);
        String result = HttpUtil.get(ACCESS_TOKEN_URL,paramMap);
        JSONObject resultJson = JSONUtil.parseObj(result);
        String token = resultJson.get("access_token",String.class);
        if(StrUtil.isBlank(token)){
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
        return token;
    }


    // 添加文章到草稿箱
    public static String addDart(String accessToken,Object body){
        Map<String,Object> bodyParam = new HashMap<>();

        List<Object> addParam = new ArrayList<>();

        addParam.add(body);

        bodyParam.put("articles",addParam);

        String json = JSONUtil.toJsonStr(bodyParam);

        String url = WECHAT_ADD_DRAT_URL.concat("?access_token=").concat(accessToken);

        String result = HttpRequest.post(url).body(json).execute().body();

        JSONObject resultJson = JSONUtil.parseObj(result);

        String mediaId = resultJson.get("media_id",String.class);

        return mediaId;
    }

    // 修改文章到草稿箱
    public static Boolean updateDart(String accessToken,Map<String,Object> bodyParam){

        String url = WECHAT_UPDATE_DRAT_URL.concat("?access_token=").concat(accessToken);

        String result = HttpRequest.post(url).body(JSONUtil.toJsonStr(bodyParam)).execute().body();

        JSONObject resultJson = JSONUtil.parseObj(result);

        String errCode = resultJson.get("errcode",String.class);

        if("0".equals(errCode)){
            return true;
        }else {
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
    }


    // 删除文章
    public static Boolean deleteDart(String accessToken,String mediaId){

        Map<String,Object> bodyParam = new HashMap<>();

        bodyParam.put("media_id",mediaId);

        String url = WECHAT_DELETE_DRAT_URL.concat("?access_token=").concat(accessToken);

        String result = HttpRequest.post(url).body(JSONUtil.toJsonStr(bodyParam)).execute().body();

        JSONObject resultJson = JSONUtil.parseObj(result);

        String errCode = resultJson.get("errcode",String.class);

        if("0".equals(errCode)){
            return true;
        } else {
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
    }


    // 发布文章
    public static String releaseArticle(String accessToken,String mediaId){

        Map<String,Object> bodyParam = new HashMap<>();

        bodyParam.put("media_id",mediaId);

        String url = WECHAT_SUMMIT_DRAT_URL.concat("?access_token=").concat(accessToken);

        String result = HttpRequest.post(url).body(JSONUtil.toJsonStr(bodyParam)).execute().body();

        JSONObject resultJson = JSONUtil.parseObj(result);

        String errCode = resultJson.get("errcode",String.class);

        String publishId = "";
        if("0".equals(errCode)){
            publishId = resultJson.get("publish_id",String.class);
        } else {
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
        return publishId;
    }

    // 轮询发布状态
    public static String getArticleStatus(String accessToken,String publishId){

        Map<String,Object> bodyParam = new HashMap<>();

        bodyParam.put("publish_id",publishId);

        String url = WECHAT_FOREACH_STATUS_URL.concat("?access_token=").concat(accessToken);

        String result = HttpUtil.post(url,bodyParam);

        JSONObject resultJson = JSONUtil.parseObj(result);

        String errCode = resultJson.get("errcode",String.class);

        //发布状态，0:成功, 1:发布中，2:原创失败, 3: 常规失败, 4:平台审核不通过, 5:成功后用户删除所有文章, 6: 成功后系统封禁所有文章
        String publishStatus = "";
        if("0".equals(errCode)){
            publishStatus = resultJson.get("publish_status",String.class);
        } else {
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
        return publishStatus;
    }

    public static Map<String,String> uploadFile(String accessToken, String path,String type){

        Map<String,Object> bodyParam = new HashMap<>();

        File media = new File(path);

        bodyParam.put("media", media);

        String url = WECHAT_UPLOAD_FILE.concat("?access_token=").concat(accessToken).concat("&type=").concat(type);

        String result = HttpRequest.post(url).form(bodyParam).execute().body();

        JSONObject resultJson = JSONUtil.parseObj(result);

        String errCode = resultJson.get("errcode",String.class);

        Map<String,String> returnMap = new HashMap<>();
        if(StrUtil.isBlank(errCode) || "0".equals(errCode)){
            String media_id = resultJson.get("media_id",String.class);
            String imageUrl = resultJson.get("url",String.class);
            returnMap.put("media_id",media_id);
            returnMap.put("url",imageUrl);
            media.delete();
        } else {
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
        return returnMap;
    }

    /**
     * 添加自定义菜单
     */
    public static boolean addMenu(String accessToken, Object body) {

        Map<String,Object> bodyParam = new HashMap<>();


        bodyParam.put("button",body);


        String url = WECHAT_MENU_CREATE_URL.concat("?access_token=").concat(accessToken);

        //String result = HttpUtil.post(url,JSONUtil.toJsonStr(bodyParam));
        String result = HttpRequest.post(url).body(JSONUtil.toJsonStr(bodyParam)).execute().body();

        JSONObject resultJson = JSONUtil.parseObj(result);

        if(resultJson != null){
            return true;
        }
        return false;
    }

    public static Boolean deleteMenu(String accessToken){

        String url = WECHAT_MENU_DELETE_URL.concat("?access_token=").concat(accessToken);

        //String result = HttpRequest.post(url).execute().body();
        String result = HttpRequest.post(url).body(JSONUtil.toJsonStr(null)).execute().body();
        JSONObject resultJson = JSONUtil.parseObj(result);

        String errCode = resultJson.get("errcode",String.class);

        if("0".equals(errCode)){
            return true;
        } else {
            throw new CustomException(ResultCode.ERROR.code(),resultJson.get("errmsg",String.class));
        }
    }
    



    public static void sort(String a[]) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[j].compareTo(a[i]) < 0) {
                    String temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

}
